// pages/details/details.js
const api = require('../../api/api.js')
const app = getApp()
// import Poster from '../../utils/poster';
import Poster from 'wxa-plugin-canvas/poster/poster.js'
import utils from '../../utils/utils'
// 在页面中定义激励视频广告
let videoAd = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    state: false,
    details: {},
    focus: false,
    value: '',
    commentList: [],
    commentPage: 1,
    placeholder: "我来说两句",
    zan: false,
    collection: false,
    isShowPosterModal: false,//是否展示海报弹窗
    posterImageUrl: "",//海报地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onReady(){
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  onLoad: async function (options) {
    console.log(options)
    let that = this
    let id = ''
    if (options.scene){
      id =  decodeURIComponent(options.scene)
    }else{
      id = decodeURIComponent(options.id)
    }
    wx.showShareMenu({
      withShareTicket:true,
      menus:['shareAppMessage','shareTimeline']
   })

    console.log('id', id)
    let res = await api.getdetails(id)
    console.log(res)
    this.setData({
      details: res.data,
      id: id
    })
    let commentList = await api.getPostComments(this.data.commentPage, that.data.details._id)
    if (commentList.data.length < 10) {
      that.setData({
        nomore: true,
        state: true,
        commentList: commentList.data
      })
      if (this.data.commentPage === 1) {
        that.setData({
          nodata: true
        })
      }
    } else {
      this.setData({
        commentList: commentList.data,
        state: true,
        commentPage: this.data.commentPage + 1
      })
    }
    this.getPostRelated(this.data.details._id)
    // 在页面onLoad回调事件中创建激励视频广告实例

  },
  onReady(){
    if (wx.createRewardedVideoAd) {
      videoAd = wx.createRewardedVideoAd({
        adUnitId: 'adunit-7c5c0597895bca61'
      })
      videoAd.onLoad(() => {
        console.log('视频广告加载成功')
      })
      videoAd.onError((err) => {
        console.log('视频广告加载失败',err)
      })
    }
  },
  /**
   * 输入框
   */
  bindButtonTap: function () {
    let that = this
    app.checkUserInfo(async function (userInfo, isLogin) {
      if (!isLogin) {
        that.setData({
          showLogin: true
        })
      } else {
        that.setData({
          userInfo: userInfo
        });
        that.setData({
          focus: !that.data.focus
        })
      }
    });

  },
    /**
   * 生成海报成功-回调
   * @param {} e 
   */
  onPosterSuccess(e) {
    const { detail } = e;
    wx.hideLoading({
      complete: (res) => {},
    })
    this.setData({
      posterImageUrl: detail,
      isShowPosterModal: true
    })
    console.info(detail)
  },
  /**
   * 生成海报失败-回调
   * @param {*} err 
   */
  onPosterFail(err) {
    console.info(err)
  },
    /**
   * 点击放大图片
   * @param {} e 
   */
  posterImageClick: function (e) {
    // wx.previewImage({
    //   urls: [this.data.posterImageUrl],
    // });
  },
  /**
   * 隐藏海报弹窗
   * @param {*} e 
   */
  hideModal(e) {
    this.setData({
      isShowPosterModal: false
    })
  },
    /**
   * 生成海报
   */
  onCreatePoster: async function () {
    let that = this;
    // app.checkUserInfo(async function (userInfo, isLogin) {
    //   if (!isLogin) {
    //     that.setData({
    //       showLogin: true
    //     })
    //     return
    //   } else {
    //     that.setData({
    //       userInfo: userInfo
    //     });
    //   }
    // });
    if (that.data.posterImageUrl) {
      that.setData({
        isShowPosterModal: true
      })
      return;
    }
    wx.showLoading({
      title: '海报生成中...',
      mask:true
    })
    let posterConfig = {
      width: 654*2,
      height: 800*2,
      backgroundColor: "#FEF8F3",
      debug: false,
      pixelRatio:2
        }
    var texts = [];
    texts = [
      {
        x: 11*2,
        y: 547*2,
        text: that.data.details.engmsg,
        textAlign:'left',
        fontSize: 26*2,
        color: '#333333',
        width: 654*2,
        lineNum: 3,
        lineHeight: 30*2
      },
      {
        x: 11*2,
        y: 646*2,
        baseLine: 'middle',
        text: that.data.details.chinmsg,
        fontSize: 26*2,
        color: '#333333',
        width: 654*2,
        lineNum: 3,
        lineHeight: 30*2
      },
      // {
      //   x: 201*2,
      //   y: 759*2,
      //   width: 632*2,
      //   baseLine:'middle',
      //   text: '好好生活，好好爱自己，加油！☺',
      //   fontSize: 20*2,
      //   color: '#C87756',
      //   lineNum: 1,
      //   lineHeight: 23*2
      // }
    ];

    let imageUrl = that.data.details.imgurl
    imageUrl = imageUrl.replace('http://', 'https://')
    if (/^cloud:/.test(imageUrl)){
      imageUrl = await api.getReportQrCodeUrl(imageUrl);
      imageUrl = imageUrl.fileList[0].tempFileURL
    }
    let qrCode = await api.getReportQrCodeUrl(that.data.details.qrCode);
    console.log(qrCode)
    let qrCodeUrl = qrCode.fileList[0].tempFileURL
    if (qrCodeUrl == "") {
      let addReult = await api.addPostQrCode(that.data.details._id)
      console.log(addReult)
      qrCodeUrl = addReult.result[0].tempFileURL
    }
    console.info(qrCodeUrl)
    var images = [
      {
        width: 632*2,
        height: 466.8*2,
        x: 11*2,
        y: 38.12*2,
        url: imageUrl,//海报主图
      },

      {
        width: 169*2,
        height: 169*2,
        x: 453*2,
        y: 527*2,
        borderRadius:169,
        url: qrCodeUrl,//二维码的图
      }
    ];
    posterConfig.texts = texts; //海报的文字
    posterConfig.images = images;
    that.setData({ posterConfig: posterConfig }, () => {
      Poster.create(true);    //生成海报图片
    });

  },

  /**
   * 提交评论
   * @param {} e 
   */
  formSubmit: function (e) {
    let subcributeTemplateId = 'xjFRhHQCb-2GbnXKYO7NU57s7qJao22_SkRBBOOX1_4'
    try {
      let that = this;
      let commentPage = 1
      let content = that.data.value;
      console.info(content)
      if (content == undefined || content.length == 0) {
        wx.showToast({
          title: '请输入内容',
          icon: 'none',
          duration: 1500
        })
        return
      }

      wx.requestSubscribeMessage({
        tmplIds: [subcributeTemplateId],
        success(res) {
          wx.showLoading({
            title: '加载中...',
          })
          console.info(res)
          console.info(res[subcributeTemplateId])
          that.submitContent(content, commentPage, res[subcributeTemplateId]).then((res) => {
            console.info(res)
            wx.hideLoading()
          })
        },
        fail(res) {
          console.info(res)
          wx.showToast({
            title: '程序有一点点小异常，操作失败啦',
            icon: 'none',
            duration: 1500
          })
        }
      })
    } catch (err) {
      wx.showToast({
        title: '程序有一点点小异常，操作失败啦',
        icon: 'none',
        duration: 1500
      })
    }
  },
  /**
   * 获取订阅消息
   */
  submitContent: async function (content, commentPage, accept) {
    let that = this
    let checkResult = await api.msgSecCheck(content)
    console.log(checkResult.result)
    if (!checkResult.result) {
      wx.showToast({
        title: '评论内容存在敏感信息',
        icon: 'none',
        duration: 2000
      })
      return
    }
    console.log('commentId', that.data.commentId)
    if (!that.data.commentId) {
      var data = {
        postId: that.data.details._id,
        cNickName: that.data.userInfo.nickName,
        cAvatarUrl: that.data.userInfo.avatarUrl,
        cOpenId: app.globalData.openid,
        timestamp: new Date().getTime(),
        createDate: utils.dateFormat("YYYY-mm-dd HH:MM:SS", new Date),
        comment: content,
        childComment: [],
        flag: 1
      }
      console.log('data', data)
      console.log('openid', app.globalData.openid)
      await api.addPostComment(data, accept)
    } else {
      var childData = [{
        cOpenId: app.globalData.openid,
        cNickName: that.data.userInfo.nickName,
        cAvatarUrl: that.data.userInfo.avatarUrl,
        timestamp: new Date().getTime(), //new Date(),
        createDate: utils.dateFormat("YYYY-mm-dd HH:MM:SS", new Date),
        comment: content,
        tNickName: that.data.toName,
        tOpenId: that.data.toOpenId,
        flag: 1
      }]
      console.log('childData', childData)
      await api.addPostChildComment(that.data.commentId, that.data.details._id, childData, accept)
    }

    let commentList = await api.getPostComments(commentPage, that.data.details._id)
    console.log('commentList', commentList)
    if (commentList.data.length === 0) {
      that.setData({
        nomore: true
      })
      if (commentPage === 1) {
        that.setData({
          nodata: true
        })
      }
    } else {
      let post = that.data.details;
      post.totalComments = post.totalComments + 1
      that.setData({
        commentPage: commentPage + 1,
        commentList: commentList.data,
        commentContent: "",
        nomore: false,
        nodata: false,
        post: post,
        commentId: "",
        placeholder: "评论...",
        focus: false,
        toName: "",
        toOpenId: ""
      })
    }

    wx.showToast({
      title: '提交成功',
      icon: 'success',
      duration: 1500
    })
  },

  /**
   * 收藏功能
   */
  postCollection: async function () {
    wx.showLoading({
      title: '加载中...',
    })
    let COLLECTION = 1
    try {
      let that = this;
      let collection = that.data.collection;
      if (collection === true) {
        let result = await api.deletePostCollectionOrZan(that.data.details._id, COLLECTION)
        console.info(result)
        that.setData({
          collection: !that.data.collection
        })
        wx.showToast({
          title: '已取消收藏'
        })
      } else {

        let data = that.data.details
        data.type = COLLECTION
        data._openid = app.globalData.openid
        console.log(data)
        await api.addPostCollection(data)
        that.setData({
          collection: !that.data.collection
        })
        wx.showToast({
          title: '已收藏'
        })
      }
    } catch (err) {
      wx.showToast({
        title: '程序有一点点小异常，操作失败啦'
      })
      console.info(err)
    } 

  },
  /**
   * 点赞功能
   */
  postZan: async function () {
    wx.showLoading({
      title: '加载中...',
    })
    let ZANTYPE = 2
    try {
      let that = this;
      let zan = that.data.zan;
      if (zan === true) {
        let result = await api.deletePostCollectionOrZan(that.data.details._id, ZANTYPE)
        console.info(result)
        that.setData({
          zan: !that.data.zan
        })
        console.log('已取消点赞')
        wx.showToast({
          title: '已取消点赞'
        })
      } else {
        let data = that.data.details
        data.type = ZANTYPE
        data._openid = app.globalData.openid
        console.log(1)

        let res = await api.addPostZan(data)
        console.log(res)
        console.log(2)
        that.setData({
          zan: !that.data.zan
        })
        console.log('已赞')
        wx.showToast({
          title: '已赞'
        })
      }
    } catch (err) {
      wx.showToast({
        title: '程序有一点点小异常，操作失败啦',
        icon: 'none'
      })
      console.info(err)
    } 
  },
  /**
   * 获取收藏和喜欢的状态
   */
  getPostRelated: async function (blogId) {
    let where = {
      postId: blogId,
      openId: app.globalData.openid
    }
    let postRelated = await api.getPostRelated(where, 1);
    let that = this;
    for (var item of postRelated.data) {
      if (1 === item.type) {
        that.setData({
          collection: true
        })
        continue;
      }
      if (2 === item.type) {
        that.setData({
          zan: true
        })
        continue;
      }
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: async function () {

    try {
      let that = this;
      if (that.data.nomore === true)
        return;

      let page = that.data.commentPage;
      let commentList = await api.getPostComments(page, that.data.details._id)
      if (commentList.data.length === 0) {
        that.setData({
          nomore: true
        })
        if (page === 1) {
          that.setData({
            nodata: true
          })
        }
      } else {
        that.setData({
          commentPage: page + 1,
          commentList: that.data.commentList.concat(commentList.data),
        })
      }
    } catch (err) {
      console.info(err)
    } finally {
      wx.hideLoading()
    }

  },
  /**
   * 
   */
  traval(e) {
    console.log(e.detail.value)
    let value = e.detail.value.trim()
    this.setData({
      value: value
    })
  },
  /**
   * 点击评论内容回复
   */
  focusComment: function (e) {
    let that = this;
    let name = e.currentTarget.dataset.name;
    let commentId = e.currentTarget.dataset.id;
    let openId = e.currentTarget.dataset.openid;
    app.checkUserInfo(async function (userInfo, isLogin) {
      if (!isLogin) {
        that.setData({
          showLogin: true
        })
      } else {
        that.setData({
          userInfo: userInfo,
          commentId: commentId,
          placeholder: "回复" + name + ":",
          focus: true,
          toName: name,
          toOpenId: openId,
          focus: !that.data.focus
        });

      }
    });
  },

  /**
   * 返回上一级
   *  */
  navigateBack() {
    this.setData({
      showLogin:false
    })
    // wx.navigateBack({
    //   complete: (res) => {},
    // })
  },

  /**
   * 图片预览
   * @param {} e 
   */

  imgwraptap(e) {
    let url = e.currentTarget.dataset.src
    console.log(e)
    // wx.previewImage({
    //   urls: [url],
    // })
  },

  /**
   * 获取用户头像
   * @param {} e 
   */
  getUserInfo: function (e) {
    console.log(e.detail.userInfo)
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      
      this.setData({
        showLogin: !this.data.showLogin,
        userInfo: e.detail.userInfo
      });
    }
  },
  /**
   * 复制文字
   */
  copetext(e) {
    console.log(e)
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log(res.data) // data
          }
        })
      }
    })

  },

  /**
   * 下载图片
   */
  downloadImg: async function (e) {
    let tempFilePath = ''
    let url = e.currentTarget.dataset.url //触发函数
    console.log(url)
    let that =this
    wx.showModal({
      title: '提示',
      content: '看广告下载图片',
      success (res) {
        if (res.confirm) {
          
    //     } else if (res.cancel) {
    //       return 
    //     }
    //   }
    // })
    if (videoAd) {
      videoAd.show().catch(() => {
        // 失败重试
        videoAd.load()
          .then(() => videoAd.show())
          .catch(err => {
            console.log('激励视频 广告显示失败')
          })
      })
    }

    if (/^cloud:/.test(url)) {
      let ress =  wx.cloud.downloadFile({
        fileID: url
      }).then(res=>{
        tempFilePath = ress.tempFilePath
      })
     
      // this.savaimg(ress.tempFilePath)
      // 用户触发广告后，显示激励视频广告
    } else {
      wx.downloadFile({
        url: url,
        success(res) {
          console.log(res.tempFilePath)
          tempFilePath = res.tempFilePath
          // that.savaimg(res.tempFilePath)
        }
      });
    }
    videoAd.onClose((res)=>{
      if (res && res.isEnded) {
        // 正常播放结束，可以下发游戏奖励
        that.savaimg(tempFilePath)
      } else {
        // 播放中途退出，不下发游戏奖励
      console.log('用户提前关闭广告不发放奖励')
      }
    })

  } else if (res.cancel) {
    return 
  }
}
})
  },
  /**
   * 
   * @param {保存图片} tempFilePath 
   */
  savaimg(tempFilePath) {
    console.log(tempFilePath)

    if (typeof (tempFilePath) !== 'string' ){
      tempFilePath = this.data.posterImageUrl
    }
    wx.saveImageToPhotosAlbum({ //保存到本地
      filePath: tempFilePath,
      success(res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: function (err) {
        console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.showModal({
            title: '提示',
            content: '需要打开相册功能才能保存图片',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
                wx.openSetting({
                  success(settingdata) {
                    console.log(settingdata)
                    if (settingdata.authSetting['scope.writePhotosAlbum']) {
                      console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                    } else {
                      console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                    }
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })

        }
      }
    })
  },
/**
 * 销毁广告
 */

  onUnload(){
    console.log('onUnload')
    videoAd.destroy()
    videoAd.offError()
    videoAd.offLoad()
    videoAd.offClose()
  },
  /**
   * 用户点击右上角分享
   */

  onShareAppMessage: function () {
    let id = this.data.id
    console.log('pages/details/details?id=' + id)
    return {
      title: this.data.details.chinmsg,
      path: 'pages/details/details?id=' + id,
      imageUrl:this.data.details.imgurl
    }
  }
})